package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.container.Mapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {



    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadWebapps();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(Mapper.port);
        System.out.println("=====>>>Minicat start on port：" + Mapper.port);



        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while (true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }


    }


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();


    private void loadWebapps() {
        InputStream serverAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(serverAsStream);

            Element rootElement = document.getRootElement();
            List<Element> list = rootElement.selectNodes("//Service");
            for (int i = 0; i < list.size(); i++) {
                Element element = list.get(i);
                Element connector = (Element) element.selectSingleNode("Connector");
                String port = connector.attributeValue("port");
                Mapper.setPort(Integer.valueOf(port));

                Element hostElement = (Element) element.selectSingleNode("//Host");
                String host = hostElement.attributeValue("name");
                String path = hostElement.attributeValue("appBase");
                Mapper.addHost(host, host);

                File file = new File(path);
                Arrays.asList(file.listFiles()).stream().forEach(fi -> {
                    String context = fi.getName();
                    Mapper.addContext(host, context);
                    try {
                        loadServlet(host, path, context);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(String host, String path, String context) throws FileNotFoundException {


//        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path+"/"+context+"/web.xml");
        InputStream resourceAsStream = new FileInputStream(new File(path + "/" + context + "/web.xml"));
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                //加载 path/demo1/server/LagouServlet.class
                //加载 path/demo2/server/LagouServlet.class
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:"+path+"/"+context+"/")});
                Class<?> aClass = urlClassLoader.loadClass(servletClass);


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                /*这是实例化的只是 反射实现server/LagouServlet 没有绝对路径到 实例path/demo/server/LagouServlet*/

                Mapper.addWapper(host, context, urlPattern, (HttpServlet) aClass.newInstance());

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
